\chapter{Streams Essentials}

\begin{itemize}

\item{The Streams Abstraction}

\item{Building Your Own Stream}

%\item{Add: The Relationship to Networking Classes}

\end{itemize}
Streams are Java's way of supporting I/O. A basic understanding of it
is imperative in order to do parallel and distributed network
programming in Java. You can find the streams classes in the java.io
package.  \par In this chapter, we provide an overview of the streams
classes that are provided in Java. This overview is intended to give
the reader a sufficient idea of the workings and philosophy of streams
to facilitate understanding of the networking chapter (Chapter \ref{Chapter.Networking}).
The overview begins with an explanation of the difference between
the streams classes found in Java 1.0.2 (the InputStream and
OutputStream classes) and those found in Java 1.1 and beyond (the
Reader and Writer classes). Following this overview, we present an
example that shows how to use the stream classes by creating a stream
to perform an operation familiar to Unix users: Character Translation
(the ``tr'' utility). We then show how you can extend this class to
implement the Caesar Cipher, which is one of the first examples taught
in courses on computer security and encryption.  \par The two examples
will prove helpful to understand the notion of stream layering and
composition, which is fundamental to working with Input/Output in Java
as well as computer networking, which makes use of streams extensively
for communication via network sockets. If you are already familiar
with streams (in depth), you can safely skip to the networking
chapter.  \par

\section{The Streams Abstraction}
As mentioned in the chapter introduction, streams represent one of the
most powerful packages in the Java programming language. To use
streams, you must import the java.io package, which is indigenous to
JDK 1.0.2, 1.1.x, and beyond. The streams classes of Java were
extended significantly between versions 1.0.2 and 1.1 and since then
have been one of the most stable, predictable, and reliable frameworks
of the Java language \par Before proceeding with a number of example
codes, it is important to understand that there are two different sets
of stream classes in Java: \par

\begin{itemize}

\item{Byte streams: InputStream and OutputStream are the base
  classes. Byte streams are intended for use primarily in applications
  that only need to use the Latin character set, which is an 8-bit
  character (of type byte in Java).}

\item{Character streams: Reader and Writer are the base
  classes. Character streams are intended for use in applications that
  are intended for worldwide use. The character encoding scheme used
  is known as UNICODE, which is the international standard (actually,
  still a de facto standard, but everyone is using it, including
  Microsoft).}

\end{itemize}
In short, you should use the character streams classes for all
application development. This is not to insinuate that the byte-stream
classes are slated for removal anytime soon. In fact, it may be
virtually impossible to move them. Most Java programmers come to know
the \texttt{InputStream} and \texttt{OutputStream} classes via a
number of standard streams found in the System package: in, out, and
err, all of which are byte streams. Fortunately for all of us, byte
streams can be freely converted to character streams. Two bridging
classes exist for this purpose: \par

\begin{itemize}

\item{InputStreamReader : This allows an input byte stream (
  InputStream ) to be used as a character input stream. We will
  actually make use of this bridging class in a number of examples.}

\item{OutputStreamWriter : This allows an output byte stream (
  OutputStream ) to be used as a character output stream. Again, we
  will be making use of this bridging class in a number of examples.}

\end{itemize}
Streams support a number of important principles that we discuss
next. Throughout the examples, we will occasionally refer to these
principles and assume that you have a high-level understanding of what
is meant: \par

\begin{itemize}

\item{Composability and layering: To do anything interesting with Java
  I/O, streams must be composed (or layered), usually from an existing
  stream. The use of composition allows you to augment the
  capabilities of an underlying stream with more powerful (and often
  more flexible) capabilities. For example, an InputStream (or Reader
  ) by default, only allows you to perform very low-level I/O
  operations, such as read() to read a single byte or read(byte[],
  offset, length) to read multiple bytes. Neither of these functions
  provides the interface wanted by most users. It is usually desired
  (in the case of text files) to be able to read a line at a time,
  which can only be done by making use of a stream class layered atop
  an InputStream .}

\item{Extensibility and filtering: One of the biggest challenges in
  I/O is in being able to support new I/O functionality. For example,
  suppose you want the ability to work with an ``encrypted'' stream
  for input. An encrypted InputStream is much like an InputStream,
  except that a decryption key must be specified when using it. As
  well, a cipher alphabet must be generated to map the cipher text
  (hopefully) to plaintext. This example appears shortly and
  demonstrates the power of Java's I/O. You can create this class and
  make use of the same read() functions without having to invent an
  entire new naming scheme and figure out what interfaces are
  appropriate.}

\end{itemize}

\section{Building Your Own Stream}
In this section, we present a complete example of how to create your
own Java stream that will be well behaved when used with existing (or
new) stream classes. This example is inspired by a useful utility in
Unix named \textbf{tr} (translate), which translates a file by
replacing characters from an input alphabet, in, with the
corresponding character in the output alphabet, out. The \textbf{tr}
utility actually has a number of bells and whistles besides being able
to perform this translation. Nevertheless, the simple character
translation problem represents an interesting example of how to extend
Java I/O streams to perform a similar task.  \par Before we begin, we
will make some assumptions: \par

\begin{itemize}

\item{The tr utility works with an input file and an output
  file. Files, as mentioned earlier, are supported via streams as a
  special case. Our tr utility will be designed so that any kind of
  stream can be used to perform the translation.}

\item{In general, we do not know what characters actually appear in
  any given stream. The design here assumes that an input character,
  if not in the input alphabet, will be left untranslated.}

\end{itemize}
The following shows the concept of character translation at a basic
level.  \par Suppose we have the following input text: 

\begin{verbatim}
The quick, lazy fox jumped over the scary cat.
\end{verbatim}

And suppose we have the
following input alphabet:
\begin{verbatim}
ABCDEFGHIJKLMNOPQRSTUVWXYZ
\end{verbatim}
And the following output alphabet:
\begin{verbatim}
abcdefghijklmnopqrstuvwxyz
\end{verbatim}

If we
translate the input text above according to the input and output
alphabets, we would get the following:
\begin{verbatim}
the quick, lazy fox jumped over the scary cat.
\end{verbatim}
The spaces, comma, and period are all left
untranslated, because none of these characters appear in the input
alphabet. This translation demonstrates how to build a simple case
translator for English letters, wherein every uppercase letter is
translated to lower case and vice versa.  \par A problem arises when
the input and output alphabets are not the same length and, in
particular, when the input alphabet has more characters than the
output alphabet. We address this problem when constructing the
translator stream by ensuring the input and output alphabets have the
same length.

Listings \ref{Listing.TranslateReader} and \ref{Listing.TranslateWriter} present 
the code for \texttt{TranslateReader} and \texttt{TranslateWriter},
respectively. Let us consider this code at a high level before diving
into the details:

\begin{itemize}

\item{In general, when defining a stream in Java, you are defining
  something called a filter. Think of a filter as being much like the
  filters encountered in real life. There is an inflow of
  characters. The filter is applied to this inflow, yielding an
  outflow. Some filters in fact do not change what is read from (or
  written to) underlying stream. (This is particularly true of many
  built-in Java classes.) Our classes perform a translation in the
  process of reading or writing. Java provides two classes for
  defining your own input and output character streams: FilterReader
  and FilterWriter .}

\item{The subclassing of filters is a bit tricky. You must take
  special care to override two methods. FilterReader provides two
  distinct read methods (overloaded names). One of the read methods is
  intended for reading a single character at a time; the other read
  method is intended for reading a block of characters at a
  time. Failing to define both methods in the subclass will cause your
  input filter to fail. The same issue applies to subclasses of
  FilterWriter . There are three write methods. You need to define all
  three to be assured of getting correct results.}

\item{When defining input and output filters, it is very often the
  case that you are working with two different classes that work
  somewhat similarly. Some input and output filters work
  symmetrically. It may be important that the two classes rely on
  identical information to perform the input or output translation. An
  example of this is shown a bit later with a Caesar cipher, which was
  an early device used for encryption. The translator we have
  discussed here is not symmetric. You can convince yourself of this
  by studying the clarifying example just presented. When you
  translate out the uppercase characters, there is no information in
  the translated text that would allow you to know what letters were
  capitalized in the original text.}

\end{itemize}
We will now study both classes in somewhat greater detail. Let us
first consider the \texttt{TranslateReader} class shown in listing
\ref{Listing.TranslateReader}. The class contains two
instance variables: \par

\begin{itemize}

\item{from : The input character set.}

\item{to : The output character set.}

\end{itemize}
The term ``set'' may be a bit of a misnomer. Here we are referring to
an ordered set of characters, where each character in the set has an
ordinal position.  \par

\textbf{TranslateReader(Reader r, String from, String to)} The
constructor initializes a \texttt{TranslateReader} instance by passing
a reference to an existing \texttt{Reader}

\texttt{r} , the input character set \texttt{from} , and the output
character set \texttt{to} . Passing a reference to a \texttt{Reader}
allows any reference to a subclass of \texttt{Reader} to also be
passed. Recall that streams are intended to be composable, and this is
why you would pass a reference to \texttt{Reader} (which is the
superclass of all character input streams) than a specific subclass,
which would limit your options.  \par

\textbf{\texttt{int read() throws IOException}} int read() throws
IOExceptionThis method is overridden to allow a single character to be
read. Note that this method is actually implemented in terms of the
other read method (discussed next), which reads a block of
characters. Notice that great care is taken to ensure that the correct
value is returned. The single character \texttt{read()} method of Java
works very similarly to the \texttt{read()} function in the C
language. This function must return the value of the character as an
integer, or it must return the end of file flag, which is -1 in
Java. The variable \texttt{oneChar} is declared as a static array of
one character, so that it can be reused between successive calls to
this function. It is needed to call the block \texttt{read()}
function, which actually handles the details of performing the
translation after reading a block of characters from the underlying
stream. This eliminates code duplication between the two read calls to
perform the translation in-line.  \par

\textbf{\texttt{int read(char[] cbuf, int off, int len)}} int
read(char[] cbuf, int off, int len)This method is overridden to allow
a block of characters to be read. The code for this method first calls
the same \texttt{read()} function in the superclass. (
\texttt{Super.read()} assures us that the superclass's method will be
called, not this method's); if you study the Java source code for
\texttt{FilterReader} , you'll discover that this causes the
originally specified \texttt{Reader's (r) read()} method to be
called. Once the block of characters has been read into an array of
characters, the translation is performed one character at a time in
place on the user-specified buffer. At the end of the call, this
buffer will contain the translated characters and not the original
characters from the underlying stream. Again, note the special care to
ensure that the block \texttt{read()} function returns what is
expected: either the number of characters read (which usually matches
the number of characters read from the underlying stream though not
required) or an end-of-file indication (-1). You must always take
special care to ensure that the end-of-file condition is handled
appropriately (i.e., returned correctly) and that any exceptions, if
handled locally, are propagated to the calling context. In the code
here, both \texttt{read()} methods will only cause exceptions when the
underlying (or superclass) \texttt{read()} method is called. Hence, it
is expected that the exception is simply being rethrown.  \par

%\begin{tabular}

\begin{lstlisting}[caption=TranslateReader class, label=Listing.TranslateReader]
public class TranslateReader extends FilterReader {
    private String from;
    private String to;
    private static char[] oneChar;

    static {
        oneChar = new char[1];
    }

    public TranslateReader(Reader r, String from, String to) {
        super(r);
        this.from = from;
        this.to = to;
    }

    public TranslateReader(Reader r) {
        super(r);
        String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String lower = "abcdefghijklmnopqrstuvwxyz";

        this.from = upper + lower;
        this.to = lower + upper;
    }

    public int read() throws IOException {
        int result = read(oneChar, 0, 1);
        if (result < 0)
            return result;
        else
            return oneChar[0];
    }

    public int read(char[] cbuf, int off, int len) throws IOException {
        int n = super.read(cbuf, off, len);
        int i;
        for (i = 0; i < n; i++) {
            int mapIndex = from.indexOf(cbuf[i]);
            if (mapIndex >= 0)
                cbuf[i] = to.charAt(mapIndex);
        }
        return n;
    }

    public static void main(String[] args) {
        StringReader sr = new StringReader("George Thiruvathukal");
        TranslateReader translateReader = new TranslateReader(sr);
        LineNumberReader lnr = new LineNumberReader(translateReader);

        try {
            String line = lnr.readLine();
            System.out.println(line);
        } catch (Exception e) {
        }
    }

}

\end{lstlisting}
The \texttt{main()} method shown in
\ref{Listing.TranslateReader} provides a quick
demonstration of a simple translator. For the purpose of this
demonstration, there is a second constructor that hard codes a simple
alphabet, where the input alphabet \texttt{from} is the set of
uppercase English letters followed by lowercase English letters, and
the \texttt{to} alphabet is the opposite. The main method makes use of
a couple of built-in \texttt{Reader} classes: \par

\textbf{\texttt{StringReader}} StringReader.This takes input from a
character string. C programmers may recall the \texttt{sscanf}
function, which allowed a string to be used for input.  \par

\textbf{\texttt{LineNumberReader}} LineNumberReader.This supports
input one line at a time, instead of requiring the use of low-level
\texttt{read()} functions.  \texttt{LineNumberReader} supports a
method, \texttt{readLine()} , that will keep calling \texttt{read()}
in the underlying stream until a newline is seen (usually LF, or
CR-LF, depending on your religious persuasion of Windows or Unix). The
\texttt{BufferedReader} class also has this capability and could well
have been used.  \texttt{LineNumberReader} will also keep count of the
number of lines read. This feature is not used in the present example.
\par

\texttt{StringReader}

\texttt{sr} is created to allow input to be read from a hard-coded
string ``Java is Great.'' Then the newly created
\texttt{TranslateReader} class is created, using the special
constructor just described. The \texttt{LineNumberReader} is
constructed so we can read one line of input at a time from the
\texttt{TranslateReader} . (There will only be one line, since all of
the input is contained in a string with no embedded newlines. There
are no limits, however, and this has been done to keep the driver code
as simple as possible.  \par The \texttt{TranslateWriter} class bears
many similarities to the \texttt{TranslateReader} class. We will not
go into the same detail here but will summarize. The constructor is
very similar to the \texttt{TranslateReader} with the notable
difference of using a \texttt{Writer} reference \texttt{w} instead of
a \texttt{Reader} reference. Again, we provide a second constructor
that will be used to hard code the translation from uppercase to
lowercase and vice versa in the main driver code.  \par There are
total of three \texttt{write()} methods to be subclassed. The first
two are very similar to the \texttt{read()} methods presented in the
\texttt{TranslateReader} . One is used to work with a single
character, while the other is used to work with a block (an array) of
characters. The key difference between these methods and the
corresponding \texttt{read()} methods is that the write operation is
performed after the translation here. This makes sense, because
translation is happening before the data are actually written to the
underlying stream. In the \texttt{read()} methods, translation clearly
must be performed after reading from the underlying stream; otherwise,
there is nothing to translate. There is a third write method, void
write(String s, int off, int len) throws IOException, which exists for
the purpose of being able to write a \texttt{String} instance more
conveniently.  \par If you are wondering why there is not a companion
\texttt{read()} method, it has something to do with the fact that the
concept of reading a string is somewhat more complicated (and ill
defined) than writing one. When you write a string, you know precisely
how many characters are in the string. This means that writing a
string can actually be formulated easily enough in terms of writing a
block of characters. The \texttt{String} class is used in this third
write method (presented next) to convert itself into a character array
(the \texttt{toCharArray()} method is used for this purpose), and then
a block write is performed. There is no similar \texttt{read()} method
because you don't know how many characters to read (i.e., when to stop
reading characters using the underlying read). The input consists
merely of raw characters. It could be useful to have a read method
that will form a string with all characters read until a certain
``delimiter'' is found in the input; however, this was probably not
considered in the design of the I/O library, because this would have
the disadvantage of assuming something that may not be true about the
underlying stream.  \par

%\begin{tabular}
\begin{lstlisting}[caption=TranslateWriter class, label=Listing.TranslateWriter]
public class TranslateWriter extends FilterWriter {
    private String from;
    private String to;
    private static char[] oneChar;
    private static char[] charArray;

    static {
        oneChar = new char[1];
    }

    public TranslateWriter(Writer w, String from, String to) {
        super(w);
        this.from = from;
        this.to = to;
    }

    public TranslateWriter(Writer w) {
        super(w);
        String upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        String lower = "abcdefghijklmnopqrstuvwxyz";

        this.from = upper + lower;
        this.to = lower + upper;
    }

    public void write(int c) throws IOException {
        oneChar[0] = (char) c;
        write(oneChar, 0, 1);
    }

    public void write(char[] cbuf, int off, int len) throws IOException {
        if (cbuf == null)
            throw new IOException();

        int i;
        for (i = 0; i < cbuf.length; i++) {
            int mapIndex = from.indexOf(cbuf[i]);
            if (mapIndex >= 0)
                cbuf[i] = to.charAt(mapIndex);
        }
        super.write(cbuf, off, len);
    }

    public void write(String s, int off, int len) throws IOException {
        if (s == null)
            throw new IOException();
        charArray = s.toCharArray();
        write(charArray, off, len);
    }


    public static void main(String[] args) {
        OutputStreamWriter osw = new OutputStreamWriter(System.out);
        TranslateWriter translateWriter = new TranslateWriter(osw);

        try {
            translateWriter.write("George K. Thiruvathukal\n");
            translateWriter.flush();
            // if you do not flush() System.out, you may see no output.
        } catch (Exception e) {
            System.err.println("Could not write to translate writer.");
            System.exit(1);
        }
    }
}

\end{lstlisting}

\begin{verbatim}

\end{verbatim}
Again, the \texttt{main()} method provides a quick demonstration of
how the \texttt{TranslateWriter} is combined with built-in Java Writer
classes to perform the translation. This time, the translation is
performed while writing instead of reading. We again provide a quick
overview of the built-in Java class being used in the main() method:
\par

\textbf{\texttt{OutputStreamWriter}} OutputStreamWriterRecall that
Java provides bridging classes to allow the byte and character I/O
classes to be combined. This is particularly important when you want
to take advantage of the standard streams, such as System.in,
System.out, and System.err, all of which are byte I/O streams. The
\texttt{OutputStreamWriter} is used so we can write character (instead
of byte) data to System.out.  \par The string ``Java is Great'' is
written to the \texttt{TranslateWriter} instance
\texttt{translateWriter} . This is the class we have been talking
about that will perform the translation on the data and then write it
to the underlying stream, which is an \texttt{OutputStreamWriter}
. The \texttt{OutputStreamWriter} object will ultimately take
responsibility for writing the translated data (without any further
translation) to the underlying stream, which is System.out. You can
run both of these programs to verify that the output is, indeed, what
is expected.  \par

%\begin{tabular}
\paragraph{For Further Exploration}
  It may be a good idea at this point to reflect on the power of what
  you have just seen. This framework provides you with unprecedented
  flexibility to define your own useful I/O classes. It may not be
  apparent just yet, but you could perform translations recursively.
  See if you can extend either of the programs in Example 10-1 or
  Example 10-2 to make use of a TranslateWriter layered atop another
  TranslateWriter (or do the same for a TranslateReader ). Does it
  work?

%\end{tabular}

\subsubsection{Caesar Cipher: Very Basic Encryption}
The ``translate'' package built into the previous section may not be
much; however, it is the basis for many interesting kinds of
streams. You could use these classes to develop an entry-level
encryption system. The technology of encryption, surprisingly, can be
traced back several centuries and is the recent subject of a recent
book studying the history of cryptography from the time of Mary, Queen
of Scots, to present\footnote{``The Code Book'' by Simon Singh}.

\par At the center of encryption technology is the ability to
``scramble'' or ``encipher'' (or both) a message. Enciphering is the
ability to perform a substitution, usually, but not limited to, a
single character at a time. This kind of cipher is known as a
monoalphabetic substitution cipher, because it works by translating
one character at a time. The idea is simple. You have the following
two alphabets: \par

\begin{itemize}

\item{The plaintext alphabet: This is an ordered character set that is
  used to compose messages.}

\item{The cipher alphabet: This is usually a permutation of the
  plaintext alphabet that can be used to encipher (translate) the
  plaintext alphabet.}

\end{itemize}
So if you wanted to build your own cipher, it should be as simple as
memorizing the input alphabet and the cipher alphabet, and then you
can decipher any enciphered message.  \par Well, not quite.  \par
First of all, there are many alphabets. In fact, if your alphabet has
\emph{N} letters, then there are \emph{N} ! ways of arranging those
\emph{N} letters. Second, chances are that you will need to send an
enciphered message to someone to be subsequently deciphered. You can
send the alphabet as the first part of the message, and the recipient
can be smart enough to construct an apporprite ``translator'' at his
or her end; however, there is a disadvantage: \par Everybody will know
your little secret. Bummer!  \par This is wherein the challenge of
developing a good encryption system lies. You need an elegant way to
transfer the key. It is a bit beyond the scope of a book on
high-performance Java computing to address this particular topic since
this chapter aims to introduce the essence of streams for an
understanding of networking-the subject of the next chapter. The
interested reader should study the RSA algorithm to understand how the
problem of key distribution is solved, using a special class of
functions called one-way functions, which are studied in modular
arithmetic.  \par Nonetheless, it is interesting to explore a way to
make a cipher that does not require us to memorize a random
permutation of letters. One scheme is known as the Caesar cipher. A
Caesar cipher works on the principle of a key being used for
enciphering and deciphering a message. The key can be used to generate
a cipher alphabet in a deterministic way using the following
algorithm: \par

\begin{itemize}

\item{Suppose we have a key, say, GEORGE.}

\item{First, begin by walking through the list of characters,
  eliminating duplicates along the way. (We cannot have any plaintext
  character mapping to the same letter.)}

\item{Now, we are left with GEOR.}

\item{Clearly, when the key is chosen, the person specifying the key
  should take care not to map a letter to itself. This is because the
  key we are now left with is going to be used to map from the
  plaintext to ciphertext. (That is, ‘A' goes to ‘G,' ‘B' goes to ‘E,'
  ‘C' goes to ‘O,' and ‘D' goes to‘R.')}

\item{Now, starting from the beginning of the alphabet, try to assign
  letters to the rest of the cipher alphabet. (In our example, we are
  start on the fourth letter of the ciphertext character set, since
  positions zero through three are already assigned to ‘G,' ‘E,' ‘O,'
  and ‘R,' respectively.) Special care should be taken to ensure that
  letters do not map to themselves.}

\end{itemize}
You can actually determine the results for any key, including GEORGE,
by running the Alphabet demo program shown in
\ref{Listing.Alphabet} . The algorithmic sketch
previously presented is actually used in the Alphabet class of this
example by the method \texttt{createCipherAlphabet()} . You can show
the cipher alphabet for any key as follows: \par

\begin{verbatim}
  String key = "your key text here";
  Alphabet a = new Alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ", key);
  System.out.println(a);
\end{verbatim}

When you run the Alphabet \texttt{main()} method, which has both a
hard-coded alphabet of English letters in their natural order and the
a hard-coded key ``GEORGE,'' you get the following cipher alphabet:
$A \rightarrow G$,
$B \rightarrow E$,
$C \rightarrow O$,
$D \rightarrow R$, 
$E \rightarrow A$, 
$F \rightarrow B$,
$G \rightarrow C$,
$H \rightarrow D$,
$I \rightarrow F$,
$J \rightarrow H$,
$K \rightarrow I$,
$L \rightarrow J$,
$M \rightarrow K$,
$N \rightarrow L$,
$O \rightarrow M$.
$P \rightarrow N$,
$Q \rightarrow P$,
$R \rightarrow Q$,
$S \rightarrow T$,
$T \rightarrow S$, 
$U \rightarrow V$,
$V \rightarrow U$,
$W \rightarrow X$,
$X \rightarrow W$,
$Y \rightarrow Z$,
and $Z \rightarrow Y$.
(The notation $In \rightarrow Out$ indicates that the input character $In$ is
translated to $Out$ in the ciphertext.)

The Alphabet class itself should be straightforward to
understand, as all of the complexities of it are contained in the
method just described, \texttt{createCipherAlphabet()} , which uses
the foregoing algorithm to generate the cipher alphabet. For all
practical purposes, you can operate with a high-level understanding of
what this class is doing and proceed to study the
\texttt{CaesarReader} and \texttt{CaesarWriter} filters, which both
make use of the same \texttt{Alphabet} class in order to generate a
common cipher alphabet, given a key.  \par

%\begin{tabular}
\begin{lstlisting}[caption="Alphabet Translation", label=Listing.Alphabet]
public class Alphabet {

    private String in;
    private String key;
    private String out;

    public static Alphabet getAlphabet(String in, String key) {
        Alphabet a = new Alphabet(in, key);
        return a;
    }

    public String getCipherAlphabet() {
        return out;
    }

    public Alphabet(String in, String key) {
        this.in = in;
        this.key = key;
        createCipherAlphabet();
    }

    public void createCipherAlphabet() {
        out = "";
        for (int i = 0; i < key.length(); i++)
            if (out.indexOf(key.charAt(i)) < 0)
                out += key.charAt(i);

        for (int i = out.length(); i < in.length(); i++) {
            int j;
            for (j = 0; j < in.length(); j++) {
                if (i != j && out.indexOf(in.charAt(j)) < 0) {
                    out += in.charAt(j);
                    break;
                }
            }


        }
    }

    public String toString() {
        String out = "";
        for (int i = 0; i < out.length(); i++)
            out += (in.charAt(i) + ":" + out.charAt(i) + " ");
        return out;
    }

    public static void main(String args[]) {
        Alphabet a = new Alphabet("ABCDEFGHIJKLMNOPQRSTUVWXYZ",
                "GEORGE");
        System.out.println(a);
    }
}
\end{lstlisting}

%\end{tabular}
The \texttt{Alphabet} class does the most important work to construct
the cipher alphabet from any given key. It will be used by both the
\texttt{CaesarReader} and \texttt{CaesarWriter} classes, which are
presented in \ref{Listing.CaesarReader} and
\ref{Listing.CaesarWriter}.  \par Because we have
already gone through the pains of designing general-purpose classes
that can be used to perform monoalphabetic substitution as required by
the Caesar cipher, to a large extent the remainder of the story is
about extending these classes and using the \texttt{Alphabet} class to
generate the ``to'' character set. (Recall that both of our translate
classes had ``from'' and ``to'' character sets to aid in performing
the translation of characters from or to the underlying input or
output stream.)  \par Consider the code in
\ref{Listing.CaesarReader}. Class
\texttt{CaesarReader} is formed by extending \texttt{TranslateReader}
. The constructor does most of the work of setting up the
\texttt{TranslateReader} object to do most of the work for us. This is
an example of an object-oriented principle called delegation, which,
in practical terms, is a way of getting ``someone else'' to do the
work for you, the ``someone else'' being another class that basically
already does the work. The \texttt{Alphabet} class has a special
method, called a factory method, that will create an instance of the
\texttt{Alphabet} class for us, so we need not create the instance
using the new operator explicitly. Without this capability, it would
be a bit messy to initialize the superclass (i.e., call its
constructor using super), because a call to a superclass's constructor
must be among the very first statements in a constructor being
defined.  \par

%\begin{tabular}
CaesarReader.java
\begin{lstlisting}[caption=CaesarReader class, label=Listing.CaesarReader]
public class CaesarReader extends TranslateReader {

    public CaesarReader(Reader r, String inAlphabet, String key) {
        super(r, Alphabet.getAlphabet(inAlphabet, key).getCipherAlphabet(), inAlphabet);
    }

    public static void main(String[] args) {
        String key = args[0];
        InputStreamReader isr = new InputStreamReader(System.in);
        CaesarReader cr = new CaesarReader(isr, "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
                key);

        try {
            while (true) {
                int result = cr.read();
                if (result < 0)
                    break;
                System.out.write((char) result);
            }
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            System.out.flush();
        }

    }

}
\end{lstlisting}

%\end{tabular}
This is all there is to it! Aside from defining a constructor, no
additional work is required to create the \texttt{CaesarReader}
class. The \texttt{read()} functions are inherited from the
superclass, \texttt{TranslateReader} , since there is no fundamental
difference between a \texttt{CaesarReader} and
\texttt{TranslateReader} , except in how the class is constructed.
\par

%\begin{tabular}
CaesarWriter.java
\begin{lstlisting}[caption=CaesarWriter class, label=Listing.CaesarWriter]
public class CaesarWriter extends TranslateWriter {

    public CaesarWriter(Writer w, String inAlphabet, String key) {
        super(w, inAlphabet,
                Alphabet.getAlphabet(inAlphabet, key).getCipherAlphabet());
    }

    public static void main(String args[]) {
        String key = args[0];
        InputStreamReader isr = new InputStreamReader(System.in);
        BufferedReader in = new BufferedReader(isr);
        OutputStreamWriter osw = new OutputStreamWriter(System.out);
        CaesarWriter cw = new CaesarWriter(osw,
                "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
                key);
        try {

            while (true) {
                String input = in.readLine();
                if (input == null) break;
                cw.write(input + "\n");
                cw.flush();
            }
        } catch (Exception e) {
            return;
        }
    }

}

\end{lstlisting}

%\end{tabular}
The following box shows a sample session with the
\texttt{CaesarReader} and \texttt{CaesarWriter} classes developed in
the foregoing discussion.  \par

%\begin{tabular}
The Session (This was run with the ‘bash' shell on RedHat Linux.)
\begin{verbatim}
  The following shows how to encipher input lines (plaintext) using
  the key JAVATHREADS. Note that you can enter as many lines of text
  as desired. The last line must be terminated by ^D on Unix (^Z on
  Windows/DOS).

  $ java com.toolsofcomputing.streams.CaesarWriter JAVATHREADS


  THIS IS A TEST OF THE EMERGENCY BROADCAST SYSTEM.

  PDSO SO J PHOP KR PDH HGHNEHIVZ ANKJTVJOP OZOPHG.

  THIS IS AN EXAMPLE OF WHAT HAPPENS WHEN YOU USE SOMETHING 123
  
  PDSO SO JI HWJGLFH KR XDJP DJLLHIO XDHI ZKQ QOH OKGHPDSIE 123

  NOT IN THE

  IKP SI PDH

  ALPHABET.

  JFLDJAHP.

  ^D


  The following shows what happens when you try to decipher the
  message with the wrong key. The text used has been cut and pasted
  from the enciphered output just shown.

  $ java com.toolsofcomputing.streams.CaesarReader JAVA


  PDSO SO J PHOP KR PDH HGHNEHIVZ ANKJTVJOP OZOPHG.
  
  QFTP TP A QJPQ LS QFJ JIJOGJKCY BOLAUCAPQ PYPQJI.

  ^D


  The following shows what happens when the proper key is supplied
  instead.

  $ java com.toolsofcomputing.streams.CaesarReader JAVATHREADS


  PDSO SO J PHOP KR PDH HGHNEHIVZ ANKJTVJOP OZOPHG.
  
  THIS IS A TEST OF THE EMERGENCY BROADCAST SYSTEM.

  ^D

\end{verbatim}

%\end{tabular}
A natural question to ask at this point is, ``Does one really need to
know how to create his or her own stream classes in order to do
multithreaded or distributed computing with Java?'' Not
necessarily. On the other hand, a knowledge of the streams mechanism
can be helpful when a built-in stream does not exist for what is
needed. Java supports fully encrypted streams as part of the Java
Cryptography Extensions, so it is unlikely that you would make
specific use of the Caesar cipher.  \par

\section{Chapter Wrap-Up}
Streams, Java's I/O framework, are an essential part of network
programming. The intention of this chapter has been to introduce the
basic ideas of streams, which include the principles of extension and
layering. What makes streams different in Java from the interfaces
found in C and C++ is the ease of which custom streams can be built
and almost immediately put to use.  \par What we have not covered here
are the multitude of streams classes that are provided in the Java
language proper. This has been done partly by design as there are
already a number of references on Java that provide an introductory
treatment of the many streams classes provided in Java. In the
networking chapter we will employ a number of useful Java streams to
implement basic network services. In the last chapter on coordination,
we will demonstrate that the availability of these powerful streams
can be used to build a fancy coordination system (the Memo system)
that can be used to write parallel programs that are to be run on a
network of computers.  \par

\section{Exercises}

\begin{enumerate}

\item{The 2nd constructor in example 10-1 clearly does not belong in
  this class. It initializes some default ``to'' and ``from''
  character sets. What translation is being performed if this
  constructor is used? Is this something that would normally be done
  in an actual translation application? (The author admits to being
  too lazy to move this code, which had been added for quick
  testing. Nevertheless, it makes for a good exercise to make you
  think about how the code is really working.)}

\item{Based on your answer to the previous question, develop two
  subclasses of the TranslateReader and TranslateWriter classes that
  can convert a character stream to all uppercase or to all
  lowercase. This means that you will effectively need to write four
  classes, although you may be able to combine functionality.}

\item{The TranslateReader and TranslateWriter classes presently are
  limited to one to one character translation. That is, a single
  character can be mapped to a single character. This can make it
  difficult to build a useful class of translators that operate on
  more than a single character, such as one that is commonly found
  when moving between DOS/Windows and Unix platforms: converting
  carriage returns to carriage return/linefeed or vice versa. Extend
  the TranslateReader and TranslateWriter to support such a
  scheme. (This may keep you busy.) Write a translator that can either
  remove or add the linefeed character as described.}

\item{Rewrite the SMA classes to use DataInputStream and
  DataOutputStream to read and write messages, respectively. You will
  need to write the table of parameters in such a way that allows you
  to easily put it back together again when reading it. Note: Do not
  use object serialization to do this. Object serialization takes all
  the fun out of thinking about how to do what is being asked here in
  this question, and it is somewhat unnecessary, since we are just
  encoding a table of key, value pairs, where the keys and values are
  all Strings.}

\end{enumerate}

